package cn.john.hrm.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

public class MyAuthorDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("message", " 对不起,认证失败!!!");
        map.put("resultObj", null);
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        String result = JSON.toJSONString(map);
        //使用响应对象将 结果返回回去
        //设置响应格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(result);
        writer.close();
    }
}
